package com.gel.codegeneration.core.handler;

import com.gel.codegeneration.common.enums.ChatHistoryMessageTypeEnum;
import com.gel.codegeneration.model.entity.User;
import com.gel.codegeneration.service.ChatHistoryService;
import reactor.core.publisher.Flux;

/**
 * @BelongsProject: code-generation-platform
 * @BelongsPackage: com.gel.codegeneration.core.handler
 * @Author: gel
 * @CreateTime: 2025-08-24  18:20
 * @Description: TODO 简单文本流处理器
 * @Version: 1.0
 */
public class SimpleTextStreamHandler {

    public Flux<String> handle(Flux<String> originFlux, ChatHistoryService chatHistoryService, Long appId, User loginUser) {
        //收集数据用于后端记忆格式
        StringBuffer aiResponse = new StringBuffer();
        return originFlux.map(
                chunk->{
                    //收集ai响应的内容
                    aiResponse.append( chunk);
                    return chunk;
                }).doOnComplete(()->{
                    //存储ai回复到mysql
                    chatHistoryService.addChatMessage(appId,aiResponse.toString(), ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
                }).doOnError(e->{
                    String errorMessage = "ai回复失败"+e.getMessage();
                    chatHistoryService.addChatMessage(appId,errorMessage, ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
        });
    }
}
